package pers.richard.ormybatis.bean.mapping;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.stream.Stream;

import cn.hutool.core.util.StrUtil;
import pers.richard.ormybatis.bean.field.FieldName;
import pers.richard.ormybatis.bean.sql.OperationExpressionBean;
import pers.richard.ormybatis.bean.sql.Update;
import pers.richard.ormybatis.util.CaseFormatUtil;

/**
 * 修改update mapping参数bean
 */
public class UpdateMappingBean extends BaseMappingBean{
	/** 修改update字段构造器  */
	private Update update;
	
	public UpdateMappingBean(){}
	
	public UpdateMappingBean(String tableName, String primaryKeyName, Update update, Class poClz, boolean lowerUnderscore) {
		super(tableName, primaryKeyName);
		this.update = update;
		//查找更新j时间字段属性名
		String updateFieldName = Stream.of(poClz.getDeclaredFields()).map(Field::getName).filter(n -> StrUtil.equalsAnyIgnoreCase(n, UPDATE_FIELD_PROPERTY) ).findFirst().orElse(null);
		if (StrUtil.isNotBlank(updateFieldName)) {
			OperationExpressionBean operationExpressionBean = update.getUpdateField().stream().filter(p -> p.getField().equals(CaseFormatUtil.toLowerUnderscore(updateFieldName))).findFirst().orElse(null);
			if (operationExpressionBean == null) {
				update.updateEq(new FieldName(updateFieldName), new Date());
			}
		}
		//查找更新版本号字段属性名
		String updateVersionFieldName = Stream.of(poClz.getDeclaredFields()).map(Field::getName).filter(n -> StrUtil.equalsAnyIgnoreCase(n, "updateVersion") ).findFirst().orElse(null);
		if (StrUtil.isNotBlank(updateVersionFieldName)) {
			OperationExpressionBean operationExpressionBean = update.getUpdateField().stream().filter(p -> p.getField().equals(CaseFormatUtil.toLowerUnderscore(updateVersionFieldName))).findFirst().orElse(null);
			if (operationExpressionBean == null) {
				update.updateIncr(new FieldName(updateVersionFieldName));
			}
		}
		//转换字段名
		for (OperationExpressionBean updateField : update.getUpdateField()) {
			updateField.toCaseField(lowerUnderscore);
		}
		for (OperationExpressionBean whereField : update.getWhere().getOperExpressList()) {
			whereField.toCaseField(lowerUnderscore);
		}
	}

	public Update getUpdate() {return update;}
	public void setUpdate(Update update) {this.update = update;}
}
